package domain;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Blog extends HttpServlet{

	PostsManager _pManager;
	Gson _gson;

	public Blog(){
		_pManager = new PostsManager();
		GsonBuilder b = new GsonBuilder();
		b.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		_gson = b.create();
	}

	public void addPost(String jPost){
		Gson gson = new Gson();
		PostDO p =  gson.fromJson(jPost, PostDO.class);
		p.setPubDate(new Timestamp(new Date().getTime()));
		_pManager.addPost(p);
	}
	
	public String getPostsTags() {
		String tags = _pManager.getPostsTags();
		String tagsToSend = _gson.toJson(tags);
		return tagsToSend;	
	}
	
	//Older ones
	public String getNextPosts(Date startDate, int num){
		Vector<PostDO> posts = _pManager.getNextPosts(startDate, num);
		String jPosts = _gson.toJson(posts);
		return jPosts;		
	}

	//Newer posts
	public String getPrevPosts(Date startDate, int num){
		Vector<PostDO> posts = _pManager.getPrevPosts(startDate, num);
		String jPosts = _gson.toJson(posts);
		return jPosts;		
	}
	
	//Older ones
	public String getNextPostsByTags(Date startDate,String tags, int num){
		Vector<PostDO> posts = 
			_pManager.getNextPostsWithTags(startDate, _gson.fromJson(tags, String.class), num);
		String jPosts = _gson.toJson(posts);
		return jPosts;		
	}

	//Newer ones
	public String getPrevPostsByTags(Date startDate, String tags, int num){
		Vector<PostDO> posts = 
			_pManager.getPrevPostsWithTags(startDate, _gson.fromJson(tags, String.class), num);
		String jPosts = _gson.toJson(posts);
		return jPosts;		
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		System.out.println("doGet");
		PrintWriter out = resp.getWriter();
		String postsToSend  = null;

		if(req.getParameter("getallposts") != null){
			if(req.getParameter("prev") == null){
				if(req.getParameter("date") == null){
					postsToSend = this.getNextPosts(null,10);
				}else{
					postsToSend = this.getNextPosts(new Date(Long.parseLong(req.getParameter("date"))),10);
				}
			}else{
				if(req.getParameter("date") == null){
					postsToSend = this.getPrevPosts(null,10);
				}else{
					postsToSend = this.getPrevPosts(new Date(Long.parseLong(req.getParameter("date"))),10);
				}
			}
			
			System.out.println("getting:");
			System.out.println(postsToSend);
			out.println(postsToSend);
			out.close();
			return;
			
		}else if(req.getParameter("getpoststags") != null){			
			String tags = this.getPostsTags();
			System.out.println("getting tags");
			System.out.println(tags);
			out.println(tags);
			out.close();
			return;

		}else if(req.getParameter("getpostsbetweendates") != null){
			String jsonPosts = _gson.toJson(null);
			if(req.getParameter("enddate") != null && req.getParameter("startdate") != null){

				Date startDate = new Date(Long.parseLong(req.getParameter("startdate")));
				Date endDate = new Date(Long.parseLong(req.getParameter("enddate")));
				System.out.println("getting:");
				
				if(startDate.before(endDate)){
					Vector<PostDO> posts = _pManager.getNextPosts(startDate, 10);
					Vector<PostDO> filteredPosts = new Vector<PostDO>();
					
					for(PostDO p : posts){
						if(p.getPubDate().before(endDate))
							filteredPosts.add(p);
					}
					jsonPosts = _gson.toJson(filteredPosts);
				}
				
				System.out.println(jsonPosts);
				out.println(jsonPosts);
				out.close();
				return;	
			}
		}else if(req.getParameter("getpostsbyuser") != null){
			String user = req.getParameter("getpostsbyuser");
			System.out.println("getting posts of: " + user);
			
			Vector<PostDO> postsByUser = _pManager.getPostsOf(user, 10);
			out.println(_gson.toJson(postsByUser));
			out.close();
			return;	
		}
	}
	
//	public static void main(String[] args){
//		PostsManager _pManager = new PostsManager();
//		Vector<PostDO> postsByUser = _pManager.getPostsOf("misha", 10);
//		for(PostDO p : postsByUser){
//			System.out.println(p.getLTags());
//		}
//	}


	protected void doPost(HttpServletRequest req, HttpServletResponse resp)	
			throws ServletException, IOException {
		System.out.println("doPost");

		if(req.getParameter("gettenpostsbytag") != null){
			PrintWriter out = resp.getWriter();
			String toSend = null;
			
			if(req.getParameter("prev") == null){
				if(req.getParameter("date") == null){
					toSend = this.getNextPostsByTags(null, this.getData(req), 10);
				}else{
					toSend = this.getNextPostsByTags(new Date(Long.parseLong(req.getParameter("date"))),this.getData(req), 10);
				}
			}
			else{
				if(req.getParameter("date") == null){
					toSend = this.getPrevPostsByTags(null, this.getData(req), 10);
				}else{
					toSend = this.getPrevPostsByTags(new Date(Long.parseLong(req.getParameter("date"))), this.getData(req), 10);
				}
			}
			
			out.println(toSend);
			out.close();
			return;
		}

		//in case of no parameters, add new post
		this.addPost(this.getData(req));
	}

	public String getData(HttpServletRequest req) throws IOException{
		ServletInputStream is =	req.getInputStream();
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		String line;
		StringBuffer response = new StringBuffer(); 

		while((line = rd.readLine()) != null)
			response.append(line);

		rd.close();			

		return response.toString();
	}
}
